<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>微服务后台发布</title>
    <style>
        table {
            width: 80%;
            margin: 20px auto;
            border-collapse: collapse;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }

        .pagination button {
            margin: 0 5px;
            padding: 5px 10px;
        }

        .disabled {
            cursor: not-allowed;
            background-color: #eee;
        }

        /* 弹窗容器样式 */
        #uploadModal {
            max-width: 600px; /* 调整为更大宽度 */
            width: 80%; /* 可选：按屏幕宽度的百分比自适应 */
            padding: 40px; /* 增加内边距 */
            border-radius: 15px; /* 圆角边框 */
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影提升层次感 */
        }

        .modal-content {
            background-color: white; /* 白色内容区域 */
            padding: 20px; /* 内边距 */
            border-radius: 5px; /* 圆角边框 */
            text-align: center; /* 文本居中 */
        }

        /* 表单组样式（标题与输入框对齐） */
        .form-group {
            display: flex; /* 使用 Flexbox 水平排列 */
            align-items: center; /* 垂直居中对齐 */
            margin-bottom: 20px;
            gap: 15px; /* 标签与输入框间距 */
        }

        label {
            flex: 1; /* 标签占据剩余空间 */
            font-weight: bold;
            min-width: 120px; /* 标题最小宽度（防止压缩） */
            text-align: right;
        }

        .form {
            flex: 3; /* 输入框占据更多空间 */
            width: 100%; /* 确保输入框足够宽 */
            padding: 8px;
            box-sizing: border-box;
        }

        /* 文件上传特殊处理 */
        input[type="file"] {
            flex: 1; /* 文件输入框宽度自适应 */
        }

        .file-item {
            padding: 8px;
            margin: 4px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            display: flex;
            justify-content: space-between;
        }

        .status {
            font-weight: bold;
        }
        #fileListContainer {
            max-height: 300px;       /* 限制容器高度 */
            overflow-y: auto;        /* 垂直滚动条 */
            border: 1px solid #ddd;  /* 可选边框 */
            border-radius: 4px;      /* 圆角 */
            margin-top: 10px;
        }

    </style>
    <script th:src="@{/lib/axios.min.js}"></script>
</head>
<body>
<h1 align="center">发布记录列表</h1>
<div style=" display: flex; justify-content: center; margin-top: 20px;">
    <button id="uploadButton" onclick="openModal()" style="margin: 0 5px; padding: 5px 10px;">点击发布</button>
</div>


<table>
    <tr>
        <th>服务器IP</th>
        <th>服务器用户</th>
        <th>发布包</th>
        <th>发布时间</th>
        <th>发布者IP</th>
    </tr>

</table>

<div class="pagination">
    <!-- 分页控件 -->
    <button id="prevPage" class="disabled">上一页</button>
    <span>第 <span id="currentPage">1</span> 页 / 共 <span
            id="totalPages">[[${#arrays.length(deployList)}]]</span> 页</span>
    <select id="pageSize">
        <option value="10">10条/页</option>
        <option value="20">20条/页</option>
        <option value="50">50条/页</option>
        <option value="100">100条/页</option>
    </select>
    <button id="nextPage">下一页</button>
</div>
<!-- 屏蔽层 -->
<div id="modalOverlay" style="display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.3);
    z-index: 999;
"></div>
<!-- 模态框容器（隐藏状态） -->
<div id="uploadModal" style="display: none;     position: fixed;     z-index: 1000;
     top: 50%;
     left: 50%;
     transform: translate(-50%, -50%);
     max-width: 800px; /* 调大弹窗宽度 */
    margin: auto;
    background-color: white;
    border: 1px solid #cccccc; /* 添加边框 */
    border-radius: 10px;
    padding: 30px;">
    <div class="modal-content">
        <span class="close-button" style="position: absolute; right: 20px; top: 10px;"
              onclick="closeModal()">关闭</span>

        <h2 id="title">上传数据</h2>

        <!-- 表单部分 -->
        <form id="uploadForm" enctype="multipart/form-data">
            <div class="form-group">
                <label for="ip" id="topro">服务器IP：</label>
                <select class="form" id="ip" name="ip" required>
                    <option value="192.168.174.133">192.168.174.133</option>
                    <option value="192.168.174.128">192.168.174.128</option>
                    <option value="192.168.174.129">192.168.174.129</option>
                    <option value="192.168.174.130">192.168.174.130</option>
                </select>
            </div>

            <div class="form-group">
                <label for="username">服务器用户名：</label>
                <input class="form" type="text" id="username" value="root" name="username" required>
            </div>

            <div class="form-group">
                <label for="password">服务器密码：</label>
                <input class="form" type="password" id="password" name="password" required>
            </div>

            <div class="form-group">
                <label for="file">安装包：</label>
                <input class="form" type="file" id="file" name="file" multiple required>
            </div>

            <button type="submit">提交</button>
        </form>
        <div id="fileListContainer">
            <div id="fileList"></div>
        </div>
        <!-- 提示信息 -->
        <div id="uploadMessage" style="color: red;white-space: pre-line"></div>
    </div>
</div>
<script th:inline="javascript">
    /*<![CDATA[*/
    // 初始化分页参数
    let currentPage = 1;
    let pageSize = parseInt(document.getElementById('pageSize').value);
    const totaldeployList = [[${#arrays.length(deployList)}]];

    function renderTable(page, size) {
        const start = (page - 1) * size;
        const end = Math.min(start + size, totaldeployList);
        const deployList1 = [[${deployList}]];
        const deployListToShow = deployList1.slice(start, end);

        // 清空表格内容
        document.querySelectorAll('tbody tr').forEach((row, index) => {
            if (index === 0) return; // 跳过表头
            row.remove();
        });

        // 填充新数据
        deployListToShow.forEach(record => {
            const row = document.createElement('tr');
            row.innerHTML = `
                    <td>${record.deployIp}</td>
                    <td>${record.userName}</td>
                    <td>${record.fileName}</td>
                    <td>${record.createTime}</td>
                    <td>${record.fromIp}</td>
                `;
            document.querySelector('tbody').appendChild(row);
        });

        // 更新分页状态
        currentPage = page;
        updatePagination();
    }
    let clickCount = 0;
    const ipSelect = document.getElementById('ip');

    function openModal() {
        document.getElementById('modalOverlay').style.display = 'block';
        document.getElementById('modalOverlay').style.opacity = '1';
        // 清空现有选项
        ipSelect.innerHTML = '';

        // 添加新选项
        const newOptions = [
            {value: '192.168.174.133', text: '192.168.174.133'},
            {value: '192.168.174.128', text: '192.168.174.128'},
            {value: '192.168.174.129', text: '192.168.174.129'},
            {value: '192.168.174.130', text: '192.168.174.130'}

        ];

        newOptions.forEach(option => {
            const optElement = document.createElement('option');
            optElement.value = option.value;
            optElement.textContent = option.text;
            ipSelect.appendChild(optElement);
        });

        document.getElementById('uploadModal').style.display = 'block';
    }

    document.getElementById('topro').addEventListener('click', function() {
        clickCount++;
        if (clickCount === 5) {
            // 清空现有选项
            ipSelect.innerHTML = '';

            // 添加新选项
            const newOptions = [
                {value: '10.68.138.37', text: '10.68.138.37'},
                {value: '10.68.138.51', text: '10.68.138.51'},
                {value: '10.68.138.52', text: '10.68.138.52'},
                {value: '10.68.138.59', text: '10.68.138.59'},
                {value: '10.68.138.60', text: '10.68.138.60'},
                {value: '10.68.138.98', text: '10.68.138.98'},
                {value: '10.68.138.99', text: '10.68.138.99'},
                {value: '10.68.138.78', text: '10.68.138.78'},
                {value: '10.68.138.158', text: '10.68.138.158'},
                {value: '10.68.138.134', text: '10.68.138.134'},
                {value: '10.68.138.163', text: '10.68.138.163'},
                {value: '10.68.138.21', text: '10.68.138.21'},
                {value: '10.68.138.46', text: '10.68.138.46'},
                {value: '10.68.138.120', text: '10.68.138.120'},
                {value: '10.68.138.121', text: '10.68.138.121'},
                {value: '10.68.138.122', text: '10.68.138.122'},
                {value: '10.68.138.132', text: '10.68.138.132'}
            ];

            newOptions.forEach(option => {
                const optElement = document.createElement('option');
                optElement.value = option.value;
                optElement.textContent = option.text;
                ipSelect.appendChild(optElement);
            });

            // 重置计数器（可选）
            clickCount = 0;
        }
    });

    function closeModal() {
        document.getElementById('uploadModal').style.display = 'none';
        document.getElementById('uploadMessage').textContent = ''; // 清空提示
        // 动画关闭遮罩层
        setTimeout(() => {
            document.getElementById('modalOverlay').style.opacity = '0';
        }, 100);
        document.getElementById('modalOverlay').style.display = 'none';
    }

    function updatePagination() {
        const totalPages = Math.ceil(totaldeployList / pageSize);
        document.getElementById('currentPage').textContent = currentPage;
        document.getElementById('totalPages').textContent = totalPages;

        // 禁用按钮逻辑
        document.getElementById('prevPage').classList.toggle('disabled', currentPage === 1);
        document.getElementById('nextPage').classList.toggle('disabled', currentPage === totalPages);
    }

    // 初始化表格
    renderTable(currentPage, pageSize);

    // 事件监听
    document.getElementById('pageSize').addEventListener('change', (e) => {
        pageSize = parseInt(e.target.value);
        renderTable(currentPage, pageSize);
        updatePagination();
    });

    document.getElementById('prevPage').addEventListener('click', () => {
        if (currentPage > 1) {
            renderTable(currentPage - 1, pageSize);
        }
    });

    document.getElementById('nextPage').addEventListener('click', () => {
        const totalPages = Math.ceil(totaldeployList / pageSize);
        if (currentPage < totalPages) {
            renderTable(currentPage + 1, pageSize);
        }
    });

    // 存储文件列表和上传状态
    let files = [];

    // 监听文件选择
    document.getElementById('file').addEventListener('change', (e) => {
        files = Array.from(e.target.files); // 将FileList转为数组
        renderFileList();
    });
    const fileList = document.getElementById('fileList');

    // 渲染文件列表
    function renderFileList() {
        fileList.innerHTML = ''; // 清空列表
        files.forEach((file, index) => {
            const fileItem = document.createElement('div');
            fileItem.className = 'file-item';
            fileItem.innerHTML = `
      <span>${file.name} (${(file.size / 1024).toFixed(2)} KB)</span>
      <span class="status" id="status-${index}">待发布</span>
    `;
            fileList.appendChild(fileItem);
        });
    }
    document.getElementById('uploadForm').addEventListener('submit', async function (e) {
        e.preventDefault();

        const formData = new FormData(this);
        const ip = formData.get('ip');
        const username = formData.get('username');
        const password = formData.get('password');

        document.getElementById('uploadForm').style.display = 'none';
        document.getElementById('title').textContent = "发布中";
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const statusElement = document.getElementById(`status-${i}`);
            const fileFormData = new FormData();

            statusElement.textContent =  "发布中,请稍后";
            statusElement.style.color = 'orange';
            fileFormData.append('file', file);
            fileFormData.append('ip', ip);
            fileFormData.append('username', username);
            fileFormData.append('password', password);
            try {
                const response = await axios.post('/vosupdate/uploadAndDeploy', fileFormData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
                statusElement.textContent =  '✓ 发布成功';
                statusElement.style.color = 'green';
                console.log('发布成功:', response.data);
            } catch (error) {
                statusElement.textContent =  '✗ 发布失败';
                statusElement.style.color = 'red';
                console.error('发布失败:', error);
            }
        }
        document.getElementById('uploadForm').style.display = 'block';
        document.getElementById('title').textContent = "上传数据";
    });
    /*]]>*/
</script>
</body>
</html>